import Vue from 'vue'
import VueRouter from 'vue-router'
import {getToken} from '@/utils/tokenUtil'
import store from '@/store'

Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}
const originalPush2 = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
    return originalPush2.call(this, location).catch(err => err)
}
const routes = [
    {
      path:'/login',
      component:()=>import('@/views/LoginView.vue')
    },
    {
      path:'/',
      component:()=>import('@/views/HomeView.vue'),
      children:[
        {
          path:'/dashboard/index',
          component:()=>import('@/views/dashboard/index.vue'),
        }
      ]
    }
]

const router = new VueRouter({
  mode: 'history',
  routes
})
/**路由全局前置守卫 */
router.beforeEach(async(to,from,next)=>{
  if(to.path==="/login"){
    next()
  }else{
    const token=getToken()
    if(!token){
      Vue.prototype.$message.warning("您还没有登录，请先登录")
      next("/login")
    }else{
      try {
        await Vue.prototype.$api.loginModule.getAdminInfoByTokenApi()
        //此处向状态机派发查询菜单
        // store.dispatch("menus/getAuthMenusAsync").then(response=>{
        //   router.addRoute(response)
        // })
      } catch (error) {
        Vue.prototype.$message.warning("令牌已经失效，请重新登录")
        next("/login")
      }
      next()
    }
  }
})

export default router
